package com.itheima.social.securitys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.common.utils.IdWorker;
import com.itheima.social.securitys.client.EmployeeFeginClient;
import com.itheima.social.securitys.mapper.ArchiveDetailMapper;
import com.itheima.social.securitys.mapper.ArchiveMapper;
import com.itheima.social.securitys.mapper.UserSocialMapper;
import com.itheima.social.securitys.pojo.Archive;
import com.itheima.social.securitys.pojo.ArchiveDetail;
import com.itheima.social.securitys.pojo.CityPaymentItem;
import com.itheima.social.securitys.pojo.UserSocialSecurity;
import com.itheima.social.securitys.pojo.client.UserCompanyPersonal;
import com.itheima.social.securitys.pojo.vo.UserPersonalSocial;
import com.itheima.social.securitys.service.ArchiveService;
import com.itheima.social.securitys.service.PaymentItemService;
import com.itheima.social.securitys.service.UserSocialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qiankaofei
 * @version 1.0
 * @date 2020/12/6 17:55
 */
@Service
@Transactional
public class ArchiveServiceImpl implements ArchiveService {


    @Autowired
    private ArchiveMapper archiveMapper;

    @Autowired
    private ArchiveDetailMapper archiveDetailMapper;

    @Autowired
    private UserSocialMapper userSocialMapper;

    @Autowired
    private PaymentItemService paymentItemService;

    @Autowired
    private UserSocialService userSocialService;

    @Autowired
    private EmployeeFeginClient employeeFeginClient;



    /**
     * 根据企业id和年月查询社保归档
     */
    @Override
    public Archive findArchiveByCompanyIdAndYearMonth(String companyId, String yearMonth) {
        QueryWrapper<Archive> queryWrapper=new QueryWrapper<Archive>();
        queryWrapper.and(i->i.eq("company_id",companyId).eq("years_month",yearMonth));
        //Archive archive=archiveMapper.findArchiveByCompanyIdAndYearMonth(companyId,yearMonth);
        Archive archive = archiveMapper.selectOne(queryWrapper);
        if(archive==null){
            return null;
        }
        return archive;
    }

    /**
     * 根据历史归档id查询历史归档明细
     */
    @Override
    public List<ArchiveDetail> findArchiveDetailByArchiveId(String id) {
        QueryWrapper<ArchiveDetail> queryWrapper=new QueryWrapper<ArchiveDetail>();
        queryWrapper.eq("archive_id",id);
        List<ArchiveDetail> archiveDetailList = archiveDetailMapper.selectList(queryWrapper);
        if(CollectionUtils.isEmpty(archiveDetailList)){
            return null;
        }
        return archiveDetailList;
    }

    /**
     * 当月，未归档
     */
    @Override
    public List<ArchiveDetail> getReports(String companyId, String yearMonth) throws Exception {
        List<ArchiveDetail> resultList=new ArrayList<ArchiveDetail>(0);
        List<UserPersonalSocial> userPersonalSocialList = userSocialMapper.findByPage(companyId);
        for (UserPersonalSocial u : userPersonalSocialList) {
            ArchiveDetail vo=new ArchiveDetail(u.getId(),u.getMobile(),u.getUsername(),u.getDepartmentName());
            vo.setTimeOfEntry(u.getTimeOfEntry());
            //设置个人信息
            UserCompanyPersonal personalInfoToJson = employeeFeginClient.findPersonalInfoToJson(vo.getUserId());
            vo.setUserCompanyPersonal(personalInfoToJson);
            //社保相关其他信息
            this.getOtherData(vo,yearMonth);
            resultList.add(vo);
        }
        return resultList;
    }

    public void getOtherData(ArchiveDetail vo, String yearMonth) {
        UserSocialSecurity userSocialSecurity = userSocialService.findUserSocialByUserId(vo.getUserId());
        if(userSocialSecurity == null) {
            return;
        }
        BigDecimal socialSecurityCompanyPay = new BigDecimal(0);
        BigDecimal socialSecurityPersonalPay = new BigDecimal(0);
        List<CityPaymentItem> cityPaymentItemList = paymentItemService.findCityPaymentItemListByCityId(userSocialSecurity.getProvidentFundCityId());
        for (CityPaymentItem cityPaymentItem : cityPaymentItemList) {
            if (cityPaymentItem.getSwitchCompany()) {
                BigDecimal augend;
                if (cityPaymentItem.getPaymentItemId().equals("4") && userSocialSecurity.getIndustrialInjuryRatio() != null) {
                    augend = userSocialSecurity.getIndustrialInjuryRatio().multiply(userSocialSecurity.getSocialSecurityBase());
                } else {
                    augend = cityPaymentItem.getScaleCompany().multiply(userSocialSecurity.getSocialSecurityBase());
                }
                BigDecimal divideAugend = augend.divide(new BigDecimal(100));
                socialSecurityCompanyPay = socialSecurityCompanyPay.add(divideAugend);
            }
            if (cityPaymentItem.getSwitchPersonal()) {
                BigDecimal augend = cityPaymentItem.getScalePersonal().multiply(userSocialSecurity.getSocialSecurityBase());
                BigDecimal divideAugend = augend.divide(new BigDecimal(100));
                socialSecurityPersonalPay = socialSecurityPersonalPay.add(divideAugend);
            }
        }
        vo.setSocialSecurity(socialSecurityCompanyPay.add(socialSecurityPersonalPay));
        vo.setSocialSecurityEnterprise(socialSecurityCompanyPay);
        vo.setSocialSecurityIndividual(socialSecurityPersonalPay);
        vo.setUserSocialSecurity(userSocialSecurity);
        vo.setSocialSecurityMonth(yearMonth);
        vo.setProvidentFundMonth(yearMonth);
    }


    @Autowired
    private IdWorker idWorker;

    /**
     * 设置归档
     */
    @Override
    public void setArchive(String yearMonth, String companyId) throws Exception {
        Boolean flag=false;
        //默认插入失败
        //查询历史归档
        Archive archive = this.findArchiveByCompanyIdAndYearMonth(yearMonth, companyId);
        //查询归档历史明细记录
        List<ArchiveDetail> archiveDetailList = this.getReports(companyId, yearMonth);
        //企业缴纳部分
        BigDecimal enterMoney = new BigDecimal(0);
        //个人承担部分
        BigDecimal personMoney = new BigDecimal(0);
        for (ArchiveDetail archiveDetail : archiveDetailList) {
            BigDecimal t1 = archiveDetail.getProvidentFundEnterprises() == null ? new BigDecimal(0): archiveDetail.getProvidentFundEnterprises();
            BigDecimal t2 = archiveDetail.getSocialSecurityEnterprise() == null ? new BigDecimal(0): archiveDetail.getSocialSecurityEnterprise();
            BigDecimal t3 = archiveDetail.getProvidentFundIndividual() == null ? new BigDecimal(0): archiveDetail.getProvidentFundIndividual();
            BigDecimal t4 = archiveDetail.getSocialSecurityIndividual() == null ? new BigDecimal(0): archiveDetail.getSocialSecurityIndividual();
            enterMoney.add(t1).add(t2);
            personMoney.add(t3).add(t4);
        }
        if(archive==null){
            archive= new Archive();
            archive.setId(String.valueOf(idWorker.nextId()));
            archive.setCompanyId(companyId);
            archive.setYearsMonth(yearMonth);
        }
        archive.setEnterprisePayment(enterMoney);
        archive.setPersonalPayment(personMoney);
        archive.setTotal(enterMoney.add(personMoney));
        //保存
        archiveMapper.insert(archive);
        for (ArchiveDetail archiveDetail : archiveDetailList) {
            archiveDetail.setId(String.valueOf(idWorker.nextId()));
            archiveDetail.setArchiveId(archive.getId());
            System.out.println("archiveDetail = " + archiveDetail.toString());
        }
        archiveDetailList.forEach(x->archiveDetailMapper.insert(x));
    }

    /**
     * 查询某年内社保归档列表
     */
    @Override
    public List<Archive> findHistoryArchiveList(String year,String companyId) {
        QueryWrapper<Archive> queryWrapper=new QueryWrapper<Archive>();
        queryWrapper.and(i->i.eq("company_id",companyId).likeRight("years_month",year)).orderByDesc("years_month");
        List<Archive> archiveList = archiveMapper.selectList(queryWrapper);
        if (StringUtils.isEmpty(archiveList)) {
            return null;
        }
        return archiveList;
    }

    /**
     * 根据用户id和考勤年月查询用户考勤归档明细
     */
    @Override
    public ArchiveDetail findArchiveDetailListByYearMonthAndUserId(String userId, String yearMonth) {
        QueryWrapper<ArchiveDetail> queryWrapper=new QueryWrapper<ArchiveDetail>();
        queryWrapper.and(i->i.eq("user_id",userId).eq("years_month",yearMonth));
        return  archiveDetailMapper.selectOne(queryWrapper);
    }
}
